﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.DAL.Repository;
using KBVault.DAL.Entities;
using KBVault.Web.Infrastructure;
using System.Web.UI.HtmlControls;

namespace KBVault.Web
{
    public partial class _Default : KBVaultPublicPage
    {
        protected new void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e); 
            if (!Page.IsPostBack)
            {
                htmlCompanyName.InnerText = Settings.Instance.CompanyName;
                htmlTagline.InnerText = Settings.Instance.TagLine;
                htmlJumbotronText.InnerText = Settings.Instance.JumbotronText;

                rptHotCategories.DataSource = CategoryRepository.ListHotCategories();
                rptHotCategories.DataBind();

                rptLatestArticles.DataSource = ArticleRepository.GetLatestArticles();
                rptLatestArticles.DataBind();

                rptPopularArticles.DataSource = ArticleRepository.GetPopularArticles();
                rptPopularArticles.DataBind();

                rptCategories.DataSource = CategoryRepository.List();
                rptCategories.DataBind();
            }
            var footerContainer = FindControl("htmlFooterContainer") as HtmlGenericControl;
            if (footerContainer == null)
                throw new Exception("No Footer Content Found!");
            footerContainer.Visible = true;
            footerContainer.InnerHtml += "Built by <a href=\"http://www.2bprojevi.com/kbvault\">KBVault</a> " + DateTime.Now.ToString("yyyy");
        }

        protected void rptHotCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater articlesRepeater = e.Item.FindControl("rptArticles") as Repeater;
                articlesRepeater.DataSource = (e.Item.DataItem as Category).PublicArticles.Take(Settings.Instance.ArticleCountPerCategoryOnHomePage);
                articlesRepeater.DataBind();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Session[Constants.SearchQueryKey] = txtSearch.Text;
            Response.Redirect("/Public/Search.aspx");
        }
    }
}
